{{define "cp_youtube"}} {{template "cp_head" .}}
<style>
  .yt-tbl-actions-column {
      display: flex;
      flex-direction: column;
  }
  .yt-tbl-actions-column > button { 
    margin: 5px
  }

  .card-deck {
    margin: 0 !important;
  }

</style>
<header class="page-header">
    <h2>Youtube upload feeds</h2>
</header>
{{template "cp_alerts" .}}
<!-- /.row -->
<div class="row">
    <div class="card-deck col-lg-12">
        <div class="card col-md-6 col-sm-12">
            <header class="card-header">
                <h2 class="card-title">Add New Feed</h2>
            </header>
            <div class="card-body">
                <form method="post" class="no-unsaved-popup" action="/manage/{{.ActiveGuild.ID}}/youtube">
                    <p>
                        <b>Enter a link for a YouTube channel, video, live stream, or playlist</b>
                        <br>
			<u>DISCLAIMER: Using Indirect Channel Links</u>
			<br>When using an indirect channel link, such as handle links, custom channel links, or username links, YAGPDB may add the incorrect channel.
			<br>This is because YAGPDB uses the first result from a YouTube search for these types of link, so the channel added, depends on how they're ranked by YouTube.
			<br>
			<br>If you experience an issue using these types of links, using one of the examples below is recommended.
                        <br>
                        <br>
                        <u>Examples of recommended types of links:</u>
                        <br> Direct channel link: <b>https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw</b>
                        <br> Video link: <b>https://www.youtube.com/watch?v=dQw4w9WgXcQ</b>
                        <br> Shorts link: <b>https://www.youtube.com/shorts/pBZ_2pX_8mg?feature=share</b>
			<br> Video sharing link: <b>https://youtu.be/v78KN3wZmNo</b>
			<br> Live Stream sharing link: <b>https://www.youtube.com/live/jfKfPfyJRdk?feature=share</b>
			<br> Playlist link: <b>https://www.youtube.com/playlist?list=PLEamUZtdyTMxwDNQ97Y7im8EwqRyht12R</b>
			<br>
			<u>Examples of indirect channel links (NOT RECOMMENDED):</u>
                        <br> Username link: <b>https://www.youtube.com/user/MontyPython</b>
                        <br> Custom link: <b>https://www.youtube.com/c/Taskmaster</b>
                        <br> Handle link: <b>https://www.youtube.com/@TomScottGo</b>
                        <br>
			<br>
			<u>Note:</u>
			<br>Some of these examples are flexible, so don't worry if a link you copied doesn't feature things like <b>www.</b> or <b>?feature=share</b>!
                        </br>
                        For any questions join the support server of the bot
                    </p>
                    <div class="form-group">
                        <label for="yt-channel-url">Link</label>
                        <div class="input-group input-group-sm">
                            <span class="input-group-prepend"><span
                                    class="input-group-text"></span></span>
                            <input type="text" class="form-control" placeholder="Enter link for a YouTube channel, playlist, live stream, or video" id="yt-url" name="YoutubeUrl">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="channel">Discord Channel</label>
                        <select id="channel" class="form-control" name="DiscordChannel" data-requireperms-send>
                            {{textChannelOptions .ActiveGuild.Channels nil false ""}}
                        </select>
                    </div>
                    <div class="custom-announcement-disables">
                        <span class="custom-announcement-popover">
                            {{checkbox "MentionEveryone" "new-mention-everyone" `Mention Everyone` false}}
                        </span>
                    </div>
                    <div class="form-group custom-announcement-disables">
                        <div>
                            <span class="custom-announcement-popover">
                            <select id="roles" class="multiselect form-control" multiple="multiple" name="MentionRoles" data-plugin-multiselect>
                                {{roleOptionsMulti .ActiveGuild.Roles nil nil}}
                            </select>
                            <label for="roles">Mention Roles</label>
                            </span>
                        </div>
                    </div>
                    {{checkbox "PublishLivestream" "new-publish-livestream" `Publish Livestreams` true}}
                    {{checkbox "PublishShorts" "new-publish-shorts" `Publish Shorts` true}}

                    <button type="submit" id="yt-add-btn" disabled="true" class="btn btn-success">Add</button>
                </form>
            </div>
        </div>
        <div class="card col-md-6 col-sm-12">
            <header class="card-header">
                <h2 class="card-title">Custom Announcement</h2>
            </header>
            <div class="card-body">
                <form  method="post" action="/manage/{{.ActiveGuild.ID}}/youtube/announcement">
                  <div class="form-group col mb-0">
                        {{checkbox "Enabled" "yt-announcement-enabled" `<h2 class="card-title">Enable</h2>` .Announcement.Enabled}}
                        
                        <label>YouTube Announcement Message (<span class="yt-announcement-length-counter">{{toRune .Announcement.Message|len}}</span>/5000)</label>

                        <textarea class="form-control" rows="10" id="yt-announcement-msg" name="Message" oninput="OnAnnouncementChange(this)">{{.Announcement.Message}}</textarea>
                        <span style="display: block;">
                          <button type="submit" id="yt-save-announcement-btn" class="btn btn-sm btn-success btn-block" data-async-form-alertsonly>Save</button>
                        </span>
                        <p class="help-block">
                          <b>Note: using Custom Announcement will override the default announcement message mention settings, you will have to do mentions like they are done in <a href="https://help.yagpdb.xyz/docs/reference/templates/functions/#mentions" target="_blank">custom commands</a> </b> 
                        </p>
                        <p class="help-block">
                          In addition to the full <a href="https://help.yagpdb.xyz/docs/custom-commands/" target="_blank">Custom Command syntax </a>, the following templates are also supported:</br>
                          <ul style="list-style-type: none; margin: 0; padding: 0;">
                            <li><code>{{"{{.ChannelID}}"}}</code> -  ID of the Discord Channel. </li>
                            <li><code>{{"{{.YoutubeChannelName}}"}}</code> - Name of the Youtube Channel.</li>
                            <li><code>{{"{{.YoutubeChannelID}}"}}</code> - ID of the Youtube Channel.</li>
                            <li><code>{{"{{.IsLiveStream}}"}}</code> - True, if the notification is for a livestream else False.</li>
                            <li><code>{{"{{.IsUpcoming}}"}}</code> - True, if the notification is for a scheduled release else False.</li>
                            <li><code>{{"{{.VideoID}}"}}</code> - ID of the video.</li>
                            <li><code>{{"{{.VideoTitle}}"}}</code> - Title of the video.</li>
                            <li><code>{{"{{.VideoThumbnail}}"}}</code> - Thumbnail image url of the video. </li>
                            <li><code>{{"{{.VideoDescription}}"}}</code> - Description of the video. </li>
                            <li><code>{{"{{.VideoDurationSeconds}}"}}</code> - Duration of video in seconds. </li>
                            <li><code>{{"{{.Video}}"}}</code> - Data of the video as available in the youtube API.</li>
                            <li><code>{{"{{.URL}}"}}</code> - Video url.</li>
                          </ul>
                        </p>
                    </div>
                </form>
            </div>
        </div>
        <!-- /.card -->
    </div>
    <div class="card-deck col-lg-12">
      <section class="card">
        <header class="card-header">
            <h2 class="card-title">Current subscribed channels</h2>
        </header>
        <div class="card-body">
            {{$dot := .}} {{range .Subs}}
            <form id="sub-item-{{.ID}}" data-async-form method="post" action="/manage/{{$dot.ActiveGuild.ID}}/youtube/{{.ID}}/update"><input type="text" class="hidden form-control" name="id" value="{{.ID}}"></form>{{end}}
            <table class="table table-responsive-md table-sm mb-0">
                <thead>
                    <tr>
                        <th>Youtube</th>
                        <th>Discord Channel</th>
                        <th>Mention Everyone</th>
                        <th>Mention Roles</th>
                        <th>Publish Livestreams</th>
                        <th>Publish Shorts</th>
                        <th>Enabled</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody class="yt-tbl-body">
                    {{range .Subs}}
                    <tr class="yt-tbl-row">
                        <td class="yt-tbl-column">
                            <p class="form-control-static"><a class="feedlink" href="https://youtube.com/channel/{{.YoutubeChannelID}}" target="_blank"><b>{{.YoutubeChannelName}}</b></a> - <code>{{.YoutubeChannelID}}</code></p>
                        </td>
                        <td class="yt-tbl-column">
                            <select form="sub-item-{{.ID}}" id="channel" class="form-control" name="DiscordChannel" data-requireperms-embed>
                                {{textChannelOptions $dot.ActiveGuild.Channels .ChannelID false ""}}
                            </select>
                        </td>
                        <td class="yt-tbl-column custom-announcement-disables">
                            <span class="custom-announcement-popover">
                            {{checkbox "MentionEveryone" (print "mention-everyone-" .ID) `Mention everyone` .MentionEveryone (print `form="sub-item-` .ID `"`)}}
                            </span>
                        </td>
                        <td class="yt-tbl-column custom-announcement-disables">
                            <span class="custom-announcement-popover">
                            <select form="sub-item-{{.ID}}" name="MentionRoles" class="multiselect form-control" multiple="multiple"
                              id="mention-roles" data-plugin-multiselect>
                              {{roleOptionsMulti $dot.ActiveGuild.Roles nil .MentionRoles }}
                            </select>
                            </span>
                        </td>
                        <td class="yt-tbl-column">
                            {{checkbox "PublishLivestream" (print "publish-livestream-" .ID) `Publish Livestreams` .PublishLivestream (print `form="sub-item-` .ID `"`)}}
                        </td>
                        <td class="yt-tbl-column">
                            {{checkbox "PublishShorts" (print "publish-shorts-" .ID) `Publish Shorts` .PublishShorts (print `form="sub-item-` .ID `"`)}}
                        </td>
                        <td class="yt-tbl-column">
                            {{checkbox "Enabled" (print "feed-enabled-" .ID) `` .Enabled (print `form="sub-item-` .ID `"`)}}
                        </td>
                        <td class="yt-tbl-column yt-tbl-actions-column">
                            <button form="sub-item-{{.ID}}" type="submit" class="btn btn-success" formaction="/manage/{{$dot.ActiveGuild.ID}}/youtube/{{.ID}}/update" data-async-form-alertsonly>Save</button>
                            <button form="sub-item-{{.ID}}" type="submit" class="btn btn-danger" formaction="/manage/{{$dot.ActiveGuild.ID}}/youtube/{{.ID}}/delete">Delete</button>
                        </td>
                    </tr>
                    {{end}}
                </tbody>
            </table>
        </div>
      </section>
    </div>
    <!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<script>
    $(function() {
        let ytUrlInput = $("#yt-url");
        let addButton = $("#yt-add-btn")

        ytUrlInput.on("input", function(arg) {
            let ytUrl = ytUrlInput.val()
            let ytLinkRegex = new RegExp("^(https?:\/\/)?((www|m)\.)?youtube\.com", 'g')
            let ytShortLinkRegex = new RegExp("^(https?:\/\/)?youtu\.be\/([a-zA-Z0-9_-]+).*", 'g')
            if (ytUrl && (ytLinkRegex.test(ytUrl) || ytShortLinkRegex.test(ytUrl))) {
                addButton.attr("disabled", false);
            } else {
                addButton.attr("disabled", true)
            }
        })
    })

    function OnAnnouncementChange(textArea) {
        let counter = document.querySelector(".yt-announcement-length-counter")
        let saveButton = document.querySelector("#yt-save-announcement-btn")
        let totalLength = textArea.value.length
        let newLines = textArea.value.match(/\n/g);
        if(newLines){
          totalLength += newLines.length
        }

        counter.textContent = totalLength
        if (totalLength > 5000) {
            counter.classList.add("text-danger");
            saveButton.classList.remove("btn-success")
            saveButton.classList.add("btn-disabled")
            saveButton.classList.add("disabled")
            saveButton.disabled = true
        } else {
            counter.classList.remove("text-danger");
            saveButton.disabled = false
            saveButton.classList.add("btn-success")
            saveButton.classList.remove("btn-disabled")
        }
    }

    function enablePopovers() {
        var popoverEls = document.body.getElementsByClassName("custom-announcement-popover");
        for (var i = 0; i < popoverEls.length; i++) {
            popoverEls[i].classList.add("popover-trigger");
            popoverEls[i].setAttribute("data-toggle", "popover");
            popoverEls[i].setAttribute("data-placement", "top");
            popoverEls[i].setAttribute("data-content", "Disabled when \"Custom Announcement\" is enabled.");
            popoverEls[i].setAttribute("data-trigger", "hover");
        };
    }

    function disablePopovers() {
        var popoverEls = document.body.getElementsByClassName("custom-announcement-popover");
        for (var i = 0; i < popoverEls.length; i++) {
            popoverEls[i].classList.remove("popover-trigger");
            popoverEls[i].removeAttribute("data-toggle");
            popoverEls[i].removeAttribute("data-placement");
            popoverEls[i].removeAttribute("data-content");
            popoverEls[i].removeAttribute("data-trigger");
        };
    }
    
    // Disables inputs and enable popovers
    function DisableMentions() {
        var disable = $('#yt-announcement-enabled:checked').val();
            if (disable) {
                enablePopovers();
            } else {
                disablePopovers();
            }
        var inputs = document.body.getElementsByClassName("custom-announcement-disables");
        for (var i = 0; i < inputs.length; i++) {
            if (disable) {
                $(inputs[i]).find(":input").prop("disabled", true);
            } else {
                $(inputs[i]).find(":input").prop("disabled", false);
            }
        }
    }

    DisableMentions();

    var announcementCheckbox = document.getElementById('yt-announcement-enabled');
    announcementCheckbox.addEventListener('change', (event) => { DisableMentions(); });
</script>
{{template "cp_footer" .}} {{end}}
